const User = require('../models/User');
const Assessment = require('../models/Assessment');
const Result = require('../models/Result');


const resultService = {
  // 创建新的测评结果
  async createResult(resultData) {
    const { user_id, assessment_id, score, answers } = resultData;
    
    // 验证用户和测评是否存在
    const user = await User.findById(user_id);
    const assessment = await Assessment.getById(assessment_id);
    
    if (!user) {
      throw new Error('用户不存在');
    }
    
    if (!assessment) {
      throw new Error('测评不存在');
    }
    
    // 验证分数范围
    if (score < 0 || score > 100) {
      throw new Error('分数必须在0-100之间');
    }
    
    const resultId = await Result.create({ user_id, assessment_id, score, answers });
    return resultId;
  },

  // 获取用户的测评结果
  async getUserResults(userId) {
    // 验证用户是否存在
    const user = await User.findById(userId);
    if (!user) {
      throw new Error('用户不存在');
    }
    
    const results = await Result.getByUserId(userId);
    return results;
  },

  // 获取特定测评的所有结果
  async getAssessmentResults(assessmentId) {
    // 验证测评是否存在
    const assessment = await Assessment.getById(assessmentId);
    if (!assessment) {
      throw new Error('测评不存在');
    }
    
    const results = await Result.getByAssessmentId(assessmentId);
    return results;
  },

  // 获取测评结果详情
  async getResultById(resultId) {
    const result = await Result.getById(resultId);
    if (!result) {
      throw new Error('测评结果不存在');
    }
    
    // 解析JSON格式的答案
    if (result.answers) {
      // 检查answers的类型，如果是字符串才进行解析
      if (typeof result.answers === 'string') {
        try {
          result.answers = JSON.parse(result.answers);
        } catch (e) {
          console.error('解析答案失败:', e);
          // 如果解析失败，保留原始值
        }
      }
    }
    
    // 加载对应的题库
    const questionService = require('./questionService');
    questionService.resetQuestionBank(result.assessment_id);
    
    // 重新计算各维度得分
    const dimensionScores = questionService.calculateScores(result.answers);
    
    // 生成测评报告
    const report = questionService.generateReport(dimensionScores);
    
    // 从数据库JOIN获取的assessment标题可能有不同的字段名
    // 尝试多种可能的字段名
    const assessmentTitle = result.title || result.a_title || result.assessment_title;
    
    if (assessmentTitle) {
      result.assessmentTitle = assessmentTitle;
    } else {
      // 如果没有直接从JOIN获取到标题，从Assessment表获取
      const assessment = await Assessment.getById(result.assessment_id);
      result.assessmentTitle = assessment ? assessment.title : '心理测评';
    }
    result.createdAt = result.created_at || new Date().toISOString();
    result.score = parseFloat(result.score) || 0; // 确保分数是数字类型
    result.dimensions = dimensionScores || {};
    // 确保recommendations是一个数组
    if (typeof report.suggestions === 'string' && report.suggestions.trim()) {
      result.recommendations = [report.suggestions];
    } else {
      result.recommendations = Array.isArray(report.suggestions) ? report.suggestions : [];
    }
    result.scoreDescription = report.summary || '您的测评已完成，感谢参与。';
    result.maxScore = 100; // 假设满分是100分
    result.duration = result.duration || 0; // 添加测评用时字段，默认为0
    result.description = result.description || '心理测评详情'; // 确保description字段存在
    
    return result;
  },

  // 获取所有测评结果（管理员使用）
  async getAllResults() {
    const results = await Result.getAll();
    
    // 解析所有结果中的答案
    return results.map(result => ({
      ...result,
      answers: result.answers ? JSON.parse(result.answers) : null
    }));
  },

  // 更新测评结果
  async updateResult(resultId, resultData) {
    const { score, answers } = resultData;
    
    // 验证结果是否存在
    const existingResult = await Result.getById(resultId);
    if (!existingResult) {
      throw new Error('测评结果不存在');
    }
    
    // 验证分数范围
    if (score < 0 || score > 100) {
      throw new Error('分数必须在0-100之间');
    }
    
    await Result.update(resultId, { score, answers });
    return { success: true };
  },

  // 删除测评结果
  async deleteResult(resultId) {
    // 验证结果是否存在
    const existingResult = await Result.getById(resultId);
    if (!existingResult) {
      throw new Error('测评结果不存在');
    }
    
    await Result.delete(resultId);
    return { success: true };
  },

  // 获取用户在特定测评中的结果
  async getUserResultForAssessment(userId, assessmentId) {
    const query = 'SELECT * FROM results WHERE user_id = ? AND assessment_id = ?';
    const [rows] = await require('../config/db').pool.execute(query, [userId, assessmentId]);
    
    if (rows.length === 0) {
      return null;
    }
    
    const result = rows[0];
    if (result.answers) {
      result.answers = JSON.parse(result.answers);
    }
    
    return result;
  }
};

module.exports = resultService;